package service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/blogPicture")
public class BlogPictureUpLoadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(1024 * 1024 * 10);
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setSizeMax(1024 * 1024 * 30);

        List<FileItem> items;
        try {
            items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    fileName = getFileName(fileName);
                    InputStream in = item.getInputStream();
                    byte[] arr = new byte[1024];
                    int len;

                    OutputStream out = new FileOutputStream(fileName);
                    while ((len = in.read(arr)) != -1) {
                        out.write(arr, 0, len);
                    }
                    in.close();
                    out.close();
                    PrintWriter writer = response.getWriter();
                    String finalName = fileName.substring(getServletContext().getRealPath("blogimg").length() + 1);//存储在服务器中的文件的名称
                    //注意：这里的路径中的斜杠要用/，用\\是没有用的，在editor.md中识别不出（会识别为￥），路径为/项目名/存储路径或者是项目路径
                    writer.write("{\"success\": 1, \"message\":\"success\",\"url\":" + "\"/blog/blogimg/" + finalName + "\"}");
                    writer.flush();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    private String getFileName(String fileName) {
        Random random = new Random();
        int number = random.nextInt(1000);
        String path = "/root/tomcat/apache-tomcat-8.5.78/webapps/blog/blogimg/";
        return path + System.currentTimeMillis() + number + fileName;
    }
}
